package com.daxt.controller.system;

import cn.hutool.core.codec.Base64Decoder;
import com.daxt.base.common.util.RedisUtil;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultCode;
import com.daxt.common.result.ResultUtil;
import com.daxt.mapper.sys.UserMapper;
import com.daxt.model.dic.SystemConfigType;
import com.daxt.model.dto.BaseExportParam;
import com.daxt.model.service.base.vo.BaseUser;
import com.daxt.service.UserDeptServie;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;

@Api("用户、部门管理")
@RestController
public class UserDeptController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserDeptServie UserDeptServie;

    @GetMapping("/userdept")
    public Result<String> dept(@ApiParam("单位id") @RequestParam("deptId") Long deptId,
        @ApiParam("用户id") @RequestParam("userId") Long userId){

        try {
            BaseUser baseUser= new BaseUser();
            baseUser.setId(userId);
            baseUser.setDeptIds(deptId);
            Integer rows= userMapper.updateById(baseUser);


            return ResultUtil.data(rows > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), null, deptId.toString());
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "操作异常！！！", null);
        }
    }

    @ApiOperation(value = "导入部门和人员", notes = "")
    @PostMapping("/userDept/import")
    public Result<String> importFile(@RequestBody BaseExportParam exportParam,
                                     HttpServletRequest request, HttpServletResponse response) {

        //String url = exportParam.getUrl();
        String url = Base64Decoder.decodeStr(exportParam.getUrl(), Charset.forName("UTF-8"));
        if (StringUtils.isEmpty(url))
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "请先上传要导入的文件！！！", null);
        String ossDir = RedisUtil.getSysConfig(SystemConfigType.OSS_DIR);

        try {
            Result<String> result=UserDeptServie.parseUserDeptTemplate(ossDir+url);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "操作异常，请联系管理员！！！", null);
        }
    }


}
